#include "musiclist.h"

#include<QMimeDatabase>
#include<QDebug>
#include<QSqlError>
#include<QSqlQuery>

MusicList::MusicList()
{

}

void MusicList::addMusicByUrls(const QList<QUrl> &musicUrls)
{

    //将所有的音乐加载到musicList
    for(auto e :musicUrls)
    {
        QString musicPath = e.toLocalFile();
        // 检测歌曲是否存在，如果再才能添加
        if(musicPaths.contains(musicPath))
         continue;
        // 歌曲还没有加载过，将其解析并添加到歌曲列表
         musicPaths.insert(musicPath);
         //qDebug() << musicPath;
        //先检查musicUrl的MIME类型是不是一个有效的文件
        QMimeDatabase mimeDB;
        QMimeType mimeType = mimeDB.mimeTypeForFile(e.toLocalFile());
        QString mime = mimeType.name();
        if(mime == "audio/mpeg" || mime == "audio/flac" || mime == "audio/wav")
        {

            Music music(e);
            musicList.push_back(music);
        }


    }

    for(auto str : musicPaths)
    {
        qDebug() << str;
    }
}

iterator MusicList::begin()
{
    return musicList.begin();
}

iterator MusicList::end()
{
    return musicList.end();
}

iterator MusicList::findMusicById(const QString &musicId)
{
    //在整个MusicList中查找这个MusicId是否存在
    for(iterator it = begin(); it != end(); ++it)
    {
         if(it->getMusicId() == musicId)
         {
          return it;
         }
    }
    return end();
}

void MusicList::writeToDB()
{
    for(auto music: musicList)
    {
       // 让music对象将⾃⼰写⼊数据库
       music.insertMusicToDB();
    }
    for(auto e:musicPaths)
    {
        qDebug()<<musicPaths;
    }

}

void MusicList::readFromDB()
{
    QSqlQuery query;
    query.prepare("SELECT musicId, musicName, singerName, albumName,\
                        duration, musicUrl, isLike, isHistory \
                        FROM musicInfo");

    if(!query.exec())
    {
        qDebug()<<"数据库查询失败";
        return;
    }
    while(query.next())
     {
         Music music;
         music.setMusicId(query.value(0).toString());
         music.setMusicName(query.value(1).toString());
         music.setSingerName(query.value(2).toString());
         music.setAlbumName(query.value(3).toString());
         music.setDuration(query.value(4).toLongLong());
         music.setMuicUrl(query.value(5).toString());
         music.setIsLike(query.value(6).toBool());
         music.setIsHistory(query.value(7).toBool());



         musicList.push_back(music);

         musicPaths.insert(music.getMuicUrl().toLocalFile());

    }
                  for(auto e: musicPaths)
    {
                      qDebug()<<e;
                  }

}


